package com.ddwl.message.domain.sms;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.ddwl.common.constant.BaseEnum;
import com.ddwl.common.constant.Constant;
import com.ddwl.common.constant.DataEnum;
import com.ddwl.common.constant.RedisKey;
import com.ddwl.common.exception.ParamException;
import com.ddwl.common.service.RedisService;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.common.util.UUIDGenerator;
import com.ddwl.message.domain.sms.api.SentSmsDoMainI;
import com.ddwl.message.domain.sms.bo.LoanSentSmsFlowBo;
import com.ddwl.message.domain.sms.bo.SentSmsBo;
import com.ddwl.message.domain.sms.bo.SentSmsVo;
import com.ddwl.message.domain.sms.bo.TempSentSmsBo;
import com.ddwl.message.domain.sms.constant.SmsConstant;
import com.ddwl.message.domain.sms.dao.SentSmsFlowDao;
import com.ddwl.message.domain.sms.dao.SmsTemplateDao;
import com.ddwl.message.domain.sms.dao.dto.SentSmsFlowDto;
import com.ddwl.message.domain.sms.dao.model.SmsSentFlow;
import com.ddwl.message.domain.sms.dao.model.SmsTemplate;
import com.ddwl.message.domain.sms.enums.SmsChannelEnum;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.base.RestVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类SentSmsService.java的实现描述：发送短信服务
 *
 * @author zach
 * @Date :2019-04-08 20:58.
 */
@Service
public class SentSmsDomain {
    @Resource
    private BeanFactory beanFactory;
    @Resource
    private SentSmsFlowDao sentSmsFlowDao;
    @Resource
    private SmsTemplateDao smsTemplateDao;
    @Value("${spring.profiles.active}")
    private String active;
    @Resource
    private RedisService redisService;


    public void sentSms(TempSentSmsBo tempSentSmsBo){
        SmsTemplate loanSmsTemplate = smsTemplateDao.selectLoanSmsTemplate(tempSentSmsBo.getTemplateCode());
        ParamException.isNull(loanSmsTemplate,"请输入正确的模板");
        ParamException.isTrue(loanSmsTemplate.getStatus().equals(BaseEnum.StatusEnum.DISABLE.getCode()),"模板已经停用");
        SentSmsBo sentSmsBo = createSentSmsBo(tempSentSmsBo,loanSmsTemplate);
        if(StringUtils.isNotBlank(tempSentSmsBo.getChannel())){
            ParamException.isNull(SmsChannelEnum.getChannel(tempSentSmsBo.getChannel()),"请输入正确的短信发送渠道");
        }else {
            tempSentSmsBo.setChannel(loanSmsTemplate.getChannel());
        }
        SmsSentFlow loanSentSmsFlow = createLoanSentSmsFlow(tempSentSmsBo,loanSmsTemplate,sentSmsBo.getContent());
        loanSentSmsFlow.setId(UUIDGenerator.getShortUUID());
        //获取发送短信的具体实现类
        SentSmsDoMainI sentSmsDoMainI = getSentSmsDoMainI(tempSentSmsBo.getChannel());
        RestVo<SentSmsVo> responseData;
        //发送短信
        if (Constant.PROFILE_PROD.contains(active)) {
            responseData = sentSmsDoMainI.sentSms(sentSmsBo);
        }else {
            SentSmsVo sentSmsVo = new SentSmsVo();
            sentSmsVo.setReqId(UUID.fastUUID().toString());
            sentSmsVo.setSerialId(UUID.fastUUID().toString());
            responseData = RestVo.ok(sentSmsVo);
        }
        if(200 == responseData.getCode()){
            loanSentSmsFlow.setSerialNumber(responseData.getResult().getSerialId());
            loanSentSmsFlow.setReqId(responseData.getResult().getReqId());
            loanSentSmsFlow.setStatus(SmsConstant.SmsFlowStatus.SUCCESSFUL);
            sentSmsFlowDao.insert(loanSentSmsFlow);
            redisService.getHashOps().increment(RedisKey.DATA_TODAY_CHART.getKey(), DataEnum.TodayData.MESSAGES.name(), 1);
        }else {
            loanSentSmsFlow.setStatus(SmsConstant.SmsFlowStatus.FAIL);
            loanSentSmsFlow.setResultMsg(responseData.getMsg());
            sentSmsFlowDao.insert(loanSentSmsFlow);
        }
        //保存记录
    }



    /**
     * 获取具体实现短信发送bena
     * @param channel
     * @return
     */
    public SentSmsDoMainI getSentSmsDoMainI(String channel){
        return (SentSmsDoMainI) beanFactory.getBean(SmsChannelEnum.getChannelBeanName(channel));
    }


    /**
     * 短信查询接口
     * @param dto
     * @return
     */
    public PageVo<LoanSentSmsFlowBo> getPage(PageBo<SentSmsFlowDto> dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize(), MySqlUtil.orderBy(dto.getSort(),dto.isAsc()));
        PageInfo<SmsSentFlow> info = new PageInfo(sentSmsFlowDao.getPage(dto.getParam()));
        List<LoanSentSmsFlowBo> list = BeanConverUtils.convertBeanList(info.getList(),LoanSentSmsFlowBo.class);
        return new PageVo<>(info.getTotal(),dto.getPage(),dto.getPageSize(),list);
    }

    /**
     * 短信数量查询接口
     * @param dto
     * @return
     */
    public Integer getSmsCount(SentSmsFlowDto dto) {
        Integer smsCount = sentSmsFlowDao.getSmsCount(dto);
        return smsCount;
    }


    public SentSmsBo createSentSmsBo(TempSentSmsBo tempSentSmsBo, SmsTemplate loanSmsTemplate){
        SentSmsBo sentSmsBo = new SentSmsBo();
        sentSmsBo.setSmsTime(tempSentSmsBo.getSmsTime());
        sentSmsBo.setMobile(tempSentSmsBo.getToPhone());
        sentSmsBo.setTempId(loanSmsTemplate.getTemplate());
        sentSmsBo.setSign(loanSmsTemplate.getSign());
        sentSmsBo.setTempParams(tempSentSmsBo.getTemplateParam());
        if(CollectionUtils.isEmpty(tempSentSmsBo.getTemplateParam())){
            sentSmsBo.setContent(loanSmsTemplate.getContent());
        }else{
            sentSmsBo.setContent(StrUtil.format(loanSmsTemplate.getContent(),tempSentSmsBo.getTemplateParam().toArray(new Object[tempSentSmsBo.getTemplateParam().size()])));
        }
        return sentSmsBo;
    }

    public SmsSentFlow createLoanSentSmsFlow(TempSentSmsBo tempSentSmsBo, SmsTemplate loanSmsTemplate, String content){
        SmsSentFlow loanSentSmsFlow = new SmsSentFlow();
        loanSentSmsFlow.setChannel(tempSentSmsBo.getChannel());
        loanSentSmsFlow.setContent(content);
        loanSentSmsFlow.setFromName(tempSentSmsBo.getFromName());
        if(tempSentSmsBo.getSmsTime()!=null){
            loanSentSmsFlow.setSentTime(tempSentSmsBo.getSmsTime());
        }else {
            loanSentSmsFlow.setSentTime(Instant.now());
        }
        loanSentSmsFlow.setToName(tempSentSmsBo.getToName());
        loanSentSmsFlow.setToPhone(tempSentSmsBo.getToPhone());
        loanSentSmsFlow.setTemplateCode(loanSmsTemplate.getCode());
        return loanSentSmsFlow;
    }

    /**
     * 短信发送事件
     * @return
     */
    public Map getEvent() {
        List<SmsTemplate> event = smsTemplateDao.getEvent();
        ParamException.isNull(event,"数据为空请联系管理员");
        Map<String,String> model = new HashMap<>();
        return model;
    }

    /**
     * 短信发送渠道
     * @return
     */
    public Map getChannel(){
        Map<String, String> model = new HashMap<>();
        SmsChannelEnum[] values = SmsChannelEnum.values();
        for (SmsChannelEnum value : values) {
            model.put(value.getChannel(), value.getName());
        }
        return model;
    }
}
